#include "GLTextureMvpTestWindow.h"

GLTextureMvpTestWindow::GLTextureMvpTestWindow(QWidget* parent)
	: BaseOpenGLWindow(parent)
{
	this->setWindowTitle("平面纹理MVP矩阵测试（Model->View->Projection）");
	QHBoxLayout* hLayout = new QHBoxLayout(this);
	QPushButton* btnRed = new QPushButton(this);
	btnRed->setText("执行MVP操作");
	//QPushButton* btnGreen = new QPushButton(this);
	//btnGreen->setText("缩放");
	//QPushButton* btnFlipX = new QPushButton(this);
	//btnFlipX->setText("旋转");
	hLayout->addWidget(btnRed);
	//hLayout->addWidget(btnGreen);
	//hLayout->addWidget(btnFlipX);
	hLayout->setAlignment(Qt::AlignTop);

	QTimer* timer = new QTimer(this);
	connect(btnRed, &QPushButton::clicked, [this]() {
		uModelMatrix.rotate(-55.0f, QVector3D(1.0f, 0.0f, 0.0f));//设置model矩阵（旋转）
		uViewMatrix.translate(QVector3D(0.0f, 0.0f, -3.0f));//设置view矩阵（Z轴平移）
		uProjectionMatrix.perspective(45.0f, 480.0f / 480.0f, 0.1f, 100.0f);//透视投影
		update();
		});

	/*connect(btnGreen, &QPushButton::clicked, [=]() {
		if (mScaleIndex > 3) {
			mScaleIndex = 0;
		}
		setTextureScale();
		mScaleIndex++;
		});

	connect(btnFlipX, &QPushButton::clicked, [=]() {
		timer->start(50);
		});

	connect(timer, &QTimer::timeout, [this] {
		if (mRoate > 360) {
			mRoate = 0;
		}
		setTextureRoate();
		mRoate += 10;
		});*/
}
void GLTextureMvpTestWindow::initializeGL() {
	this->initializeOpenGLFunctions();
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
	glClear(GL_COLOR_BUFFER_BIT);

	float vertices[] = {
		//     ---- 位置 ----          - 纹理坐标 -
			 0.5f,  0.5f, 0.0f,   1.0f, 1.0f,   // 右上
			 0.5f, -0.5f, 0.0f,   1.0f, 0.0f,   // 右下
			-0.5f, -0.5f, 0.0f,   0.0f, 0.0f,   // 左下
			-0.5f,  0.5f, 0.0f,    0.0f, 1.0f    // 左上
	};
	unsigned int indices[] = {
	   0, 1, 3, // first triangle
	   1, 2, 3  // second triangle
	};
	//创建VAO
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
	glBindVertexArray(VAO);

	//创建VBO
	glBindBuffer(GL_ARRAY_BUFFER, VBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

	//创建EBO
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	//告知显卡如何解析顶点数据
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
	glEnableVertexAttribArray(0);

	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
	glEnableVertexAttribArray(1);

	//解绑VBO
	//glBindBuffer(GL_ARRAY_BUFFER, 0);

	stbi_set_flip_vertically_on_load(true);
	texture = buildTexture("E:/tony/demo/visualstudio_workspace/QtForOpenCV4Tool/QtForOpenCV4Tool/bin/images/flowers.jpeg",
		GL_RGB);

	//小程序
	programId = buildAttachShaderAndReturnProgramId(":/QtForOpenCV4Tool/shader/texture_mvp_test.vert",
		":/QtForOpenCV4Tool/shader/texture_mvp_test.frag");

}

/*
* 正交投影算法，防止图片变形
*/
void GLTextureMvpTestWindow::setOrthoMProjection(float mWidth, float mHeight) {
	uProjectionMatrix.setToIdentity();//设置成为单位矩阵
	float mViewScale = (float)width() / (float)height();
	float mImgScale = mWidth / mHeight;
	float aspectRatio = 0.0f;
	if (mImgScale > mViewScale) {
		aspectRatio = mImgScale / mViewScale;
		uProjectionMatrix.ortho(-1.0f, 1.0f, -aspectRatio, aspectRatio, -1.0f, 1.0f);
	}
	else {
		aspectRatio = mViewScale / mImgScale;
		uProjectionMatrix.ortho(-aspectRatio, aspectRatio, -1.0f, 1.0f, -1.0f, 1.0f);
	}
}
void GLTextureMvpTestWindow::resizeGL(int w, int h) {
	glViewport(0, 0, w, h);
}
void GLTextureMvpTestWindow::paintGL() {
	glBindVertexArray(VAO);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texture);
	glUseProgram(programId);
	GLint ourTextureLocation = glGetUniformLocation(programId, "ourTexture");
	glUniform1i(ourTextureLocation, 0);
	glUniformMatrix4fv(glGetUniformLocation(programId, "uModel"), 1, false, uModelMatrix.data());
	glUniformMatrix4fv(glGetUniformLocation(programId, "uView"), 1, false, uViewMatrix.data());
	setOrthoMProjection((float)mWidth, (float)mHeight);
	glUniformMatrix4fv(glGetUniformLocation(programId, "uProjection"), 1, false, uProjectionMatrix.data());
	glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
}
GLuint GLTextureMvpTestWindow::buildTexture(QString textureFileName, GLint imageColorType) {
	GLuint mTexture;
	////创建纹理
	glGenTextures(1, &mTexture);
	glBindTexture(GL_TEXTURE_2D, mTexture);
	//设置纹理环绕方式
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	//设置纹理过滤方式
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	//生成纹理
	//QString path = getTexturePath(textureFileName);
	//qDebug() << path.toStdString().c_str();
	unsigned char* data = stbi_load(textureFileName.toStdString().c_str(), &mWidth, &mHeight, &mChannels, 0);
	if (data) {
		qDebug() << "图片加载成功,width=" << mWidth << ",height=" << mHeight;
		glTexImage2D(GL_TEXTURE_2D, 0, imageColorType,mWidth, mHeight, 0, imageColorType, GL_UNSIGNED_BYTE, data);
		glGenerateMipmap(GL_TEXTURE_2D);
	}
	else {
		qDebug() << "图像数据加载失败";
	}
	stbi_image_free(data);
	return mTexture;
}
GLTextureMvpTestWindow::~GLTextureMvpTestWindow()
{
}
